package cn.xw.mq.consumer;

import cn.xw.config.RabbitMQConfig;
import cn.xw.entity.MessageSendDTO;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-17 14:01
 * 死信消费者
 */
@Slf4j
@Component
public class DeadConsumer {
    /***
     * 死信消费者
     */
    @RabbitListener(queues = {RabbitMQConfig.DEAD_QUEUE}, ackMode = "MANUAL")
    public void dlxConsumerTest(@Payload String msgData, //这个是生产者发送的JSON消息
                                @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, //处理消息的编号
                                @Header(AmqpHeaders.RECEIVED_ROUTING_KEY) String routingKey,
                                Message message,
                                Channel channel) throws IOException {

        //把接收过来的JSON信息转换为对象
        MessageSendDTO messageSendDTO = JSONObject.parseObject(msgData, MessageSendDTO.class);
        //死信队列名称
        String consumerQueue = message.getMessageProperties().getConsumerQueue();
        //死信交换机名称
        String receivedExchange = message.getMessageProperties().getReceivedExchange();
        //路由key
        String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
        log.info("死信消费者从死信队列：{} 获取死信消息：{}，并处理完成手动确认", consumerQueue, messageSendDTO);
        channel.basicAck(deliveryTag, false);
    }
}
